package com.example.leetdemo.process;

import java.util.Stack;

public class Solution224 {

    public int calculate(String s) {
        s = s.replaceAll(" ", "");
        Stack<String> stack = new Stack<>();
        s = "(" + s + ")";
        String a = "";
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '(') {
                stack.push("(");
            } else if (s.charAt(i) == ')') {
                String value = rollback(stack, a);
                a = "";
                stack.push(value);
            } else if (s.charAt(i) == '+' || s.charAt(i) == '-') {
                if (!a.equals("")) {
                    stack.push(a);
                }
                stack.push(s.charAt(i) + "");
                a = "";
            } else {
                a = a + s.charAt(i);
            }
        }
        return Integer.parseInt(stack.pop());
    }

    private String rollback(Stack<String> stack, String val) {
        if (val.equals("")) {
            val = stack.pop();
        }
        if (stack.size() == 0) {
            return val;
        } else if (stack.peek().equals("(")) {
            stack.pop();
            return val;
        } else {
            String ss = stack.pop();
            if (ss.equals("+")) {
                String latest = stack.pop();
                int a = Integer.parseInt(latest) + Integer.parseInt(val);
                return rollback(stack, a + "");
            } else if (ss.equals("-")) {
                String latest = stack.pop();
                int a = Integer.parseInt(latest) - Integer.parseInt(val);
                return rollback(stack, a + "");
            } else {
                return ss;
            }
        }
    }

    public boolean canConstruct(String ransomNote, String magazine) {
        int[] c = new int[26];
        for (int i = 0; i < magazine.length(); i++) {
            c[magazine.charAt(i) - 'a']++;
        }
        for (int i = 0; i < ransomNote.length(); i++) {
            c[ransomNote.charAt(i) - 'a']--;
            if (c[ransomNote.charAt(i) - 'a'] < 0) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        Solution224 solution224 = new Solution224();
        System.err.println(solution224.calculate("2+1+2"));
    }

}
